package com.hgw.ordinary.controller;

import com.hgw.ordinary.common.FileResult;
import com.hgw.ordinary.service.UploadDownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Description: 基于服务器的文件上传与下载
 * @date 2022/10/4 11:22
 * @author itLaboratory-yanAn
 */
@RestController
@RequestMapping("UploadDownload")
public class UploadDownloadController {

    @Autowired
    UploadDownloadService uploadDownloadService;

    @Value("${file.path}")
    private String basePath;

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public FileResult upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        FileResult fileResult = new FileResult();
        if (multipartFile.isEmpty()) {
            fileResult.setSuccess(false);
            return fileResult;
        }
        // 获取用户指定的文件夹，做数据隔离（不同的业务资源放在不同的目录中）
        String dir = request.getParameter("dir");
        return uploadDownloadService.upload(multipartFile, dir);
    }


    /**
     * 文件下载
     *
     * @param path
     * @param response
     * @return
     */
    @PostMapping("/download")
    public void download(String path, HttpServletResponse response) {
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream toClient = null;
        try {
            // 1. 获取欲下载文件的相关信息：文件名.后缀名
            String targetPath = basePath + path;
            File file = new File(targetPath);
            String fileName = file.getName();

            // 2. 以流的形式从服务器中读入文件
            bufferedInputStream = new BufferedInputStream(new FileInputStream(targetPath));
            byte[] buffer = new byte[bufferedInputStream.available()];
            bufferedInputStream.read(buffer);

            // 3. 以流的方式向返回体中写出文件
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedInputStream.close();
                toClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
